package cn.kgc.shiro03.service.impl;

import cn.kgc.shiro03.entity.RolePers;
import cn.kgc.shiro03.mapper.RolePersMapper;
import cn.kgc.shiro03.util.CodeMsg;
import cn.kgc.shiro03.util.ResponseResult;
import cn.kgc.shiro03.util.TreeUtil;
import cn.kgc.shiro03.vo.PermissionVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.shiro03.entity.Permission;
import cn.kgc.shiro03.service.PermissionService;
import cn.kgc.shiro03.mapper.PermissionMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
@Transactional
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired(required = false)
    private PermissionMapper permissionMapper;

    @Autowired(required = false)
    private RolePersMapper rolePersMapper;

    @Override
    public ResponseResult treeSelect() {
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.in("is_menu", Arrays.asList(0, 1));
        List<Permission> permissions = permissionMapper.selectList(permissionQueryWrapper);
        ResponseResult responseResult = new ResponseResult();
        responseResult.setData(permissions);
        responseResult.setCode(CodeMsg.SELECT_SUCCESS.getCode());
        responseResult.setMsg(CodeMsg.SELECT_SUCCESS.getMsg());
        return responseResult;
    }

    @Override
    public ResponseResult deleteById(Integer id) {


        ResponseResult responseResult = new ResponseResult();
        //1.判定当前删除的权限 是否含有子菜单  有则阻止删除
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.eq("parent_id", id);
        List<Permission> permissions = permissionMapper.selectList(permissionQueryWrapper);

        if (permissions.size() > 0) {
            responseResult.setMsg(CodeMsg.DELETE_FAIL.getMsg());
            responseResult.setCode(CodeMsg.DELETE_FAIL.getCode());
            return responseResult;
        }

        // 2.删除权限表中的权限信息
        permissionMapper.deleteById(id);
        //  3.删除角色权限关联表中的当前权限的数据  role_permission
        QueryWrapper<RolePers> rolePersQueryWrapper = new QueryWrapper<>();
        rolePersQueryWrapper.eq("per_id", id);
        rolePersMapper.delete(rolePersQueryWrapper);
        responseResult.setMsg(CodeMsg.DELETE_SUCCESS.getMsg());
        responseResult.setCode(CodeMsg.DELETE_SUCCESS.getCode());
        return responseResult;
    }
}




